package com.wanmait.recycle.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class UpLoadController {

	@RequestMapping("manage/firstTypeUpLoad")
	@ResponseBody
	
	public String upload(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        System.out.println("收到图片!");
        MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = Murequest.getFileMap();// 得到文件map对象
        String dirPath = request.getServletContext().getRealPath("/static/rubbishType_img");

        File dir = new File(dirPath);
        if (!dir.exists())// 目录不存在则创建
            dir.mkdirs();
        String tagetFileName = "";
        for (MultipartFile file : files.values()) {
            String fileName = file.getOriginalFilename();
            int y = 0;
            for (int i = 0; i < fileName.length(); i++) {
            	char x = fileName.charAt(i);
            	if(x=='.') {
            		y=i;
            		break;
            	}
            }
            String str = fileName.substring(y);
     
            tagetFileName =  System.currentTimeMillis()+ str;
            
       
            File tagetFile = new File(dir,tagetFileName);// 创建文件对象
            if (!tagetFile.exists()) {// 文件名不存在 则新建文件，并将文件复制到新建文件中
                try {
                    tagetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    file.transferTo(tagetFile);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        return tagetFileName;
    }

}
